package ro.upt.dcda.pricezone.s1.requests.admin;

import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import ro.upt.dcda.pricezone.common.ConnectionFactory;
import ro.upt.dcda.pricezone.s1.pojo.Admin;
import ro.upt.dcda.pricezone.s1.pojo.LoggedAdmin;

public class AdminLogoutRequest {

	public boolean work(String email, String sid) {
		Session session = ConnectionFactory.getFactory().openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Query query = session.createQuery("from Admin where email=:email");
			query.setParameter("email", email);
			List<?> list = query.list();
			if (list.size() != 1) {
				return false;
			}
			Admin admin = (Admin) list.get(0);
			@SuppressWarnings("unchecked")
			Set<LoggedAdmin> logins = (Set<LoggedAdmin>) admin.getLogins();
			LoggedAdmin expiredLogin = null;
			for (LoggedAdmin login : logins) {
				if (login.getSid().equals(sid)) {
					expiredLogin = login;
					break;
				}
			}
			if (expiredLogin == null)
				return false;
			session.delete(expiredLogin);
			tx.commit();
			return true;
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
			return false;
		} finally {
			session.close();
		}
	}
}
